package code.example.hystrix.test.impl;

import code.example.tool.LogFactory;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixObservableCommand;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import rx.Observable;
import rx.Subscriber;

import java.io.ByteArrayOutputStream;
import java.util.concurrent.TimeUnit;


public class HystrixCommandVisitHttp extends HystrixCommand<String> {

     private  String url="http://www.baidu.com";
     public HystrixCommandVisitHttp(){
         super( HystrixCommandGroupKey.Factory.asKey("http"));
     }
     @Override
     protected String run() throws Exception {
          try {
               HttpGet httpGet = new HttpGet(url);
               HttpClient httpClient = HttpClients.createDefault();
               HttpResponse httpResponse = httpClient.execute(httpGet);
               int statusCode = httpResponse.getStatusLine().getStatusCode();
               ByteArrayOutputStream byteArrayOutputStream = (new ByteArrayOutputStream());
               httpResponse.getEntity().writeTo(byteArrayOutputStream);
               String result = new String(byteArrayOutputStream.toByteArray());
               LogFactory.getLog().info(Thread.currentThread().getName()+": finish:"+result);
               return result;
          }catch (Throwable e){
               LogFactory.getLog().info(Thread.currentThread().getName()+":business thread error:");
               LogFactory.getLog().error(e);
               throw e;
          }
     }
     /**
      * 降级。Hystrix会在run()执行过程中出现错误、超时、线程池拒绝、断路器熔断等情况时，
      * 执行getFallBack()方法内的逻辑
      */
     @Override
     protected String getFallback() {
          return "emptyResult";
     }
}
